1 using System.Collections;
2 using
System.Collections.Generic;
3 using
UnityEngine;
4
5 [System.Serializable]

6 public
class ObjectPoolItem {
7     
public int amountToPool;
8     
public GameObject objectToPool;
9     
public List<GameObject> pooledObjects;
10 }

11
12 public
class ObjectPooler : MonoBehaviour {
13
14     
public static ObjectPooler SharedInstance;
15
16     
public List<ObjectPoolItem> itemsToPool;
17
18     
void Awake() {
19         SharedInstance =
this;
20     }
21
22     
void Start () {
23         
foreach (ObjectPoolItem item in itemsToPool) {
24             item.pooledObjects =
new List<GameObject>();
25             
for (int i = 0; i < item.amountToPool; i++) {
26                 
// TODO: use dynamic casting? (in C#)
27                 GameObject obj = (GameObject)Instantiate(item.objectToPool);
28                 obj.SetActive(
false);
29                 item.pooledObjects.Add(obj);
30             }
31         }
32     }
33
34     
public GameObject GetPooledObject(string tag) {
35         
foreach (ObjectPoolItem item in itemsToPool) {
36 // Debug.Log (
"pooledObjects.Count: " + item.pooledObjects.Count);
37             
if (item.objectToPool.tag == tag) {
38                 
for (int i = 0; i < item.pooledObjects.Count; i++) {
39                     
if (!item.pooledObjects [i].activeInHierarchy) {
40                         
return item.pooledObjects [i];
41                     }
42                 }
43             }
44         }
45         
return null;
46     }
47
48     
void Update () {
49
50     }
51 }


Gõ tìm kiếm nhanh...